package sqlstore

import (
	"fmt"
	"errors"

	"github.com/astaxie/beego"

	"yikexing.com.cn/wyws/bus"
	"yikexing.com.cn/wyws/models"
)

func init() {

	bus.AddHandler("sql", AddFile)
	bus.AddHandler("sql", FindFileInfo)
}

func AddFile(add *models.AddFileInfo) error {

	addFild := models.FileInfo{ Name:add.Name,Size:add.Size,MongDbId:add.MongDbId}
	callback := func(tx *ThtfTx) error{
		rows, err := tx.NamedQuery(
			`INSERT INTO file_info
				(id, name, size, mong_db_id)
			       VALUES(DEFAULT,
			        :name, :size, :mong_db_id)
			    RETURNING id;`, addFild)
		if err != nil {
			beego.Debug(fmt.Sprintf("插入文件信息失败:%s", err))
			return errors.New(fmt.Sprintf("插入文件信息失败:%s", err))
		}
		for rows.Next() {
			err = rows.Scan(&addFild.Id)
		}
		return nil
	}
	er := InTransaction(callback)
	if  er != nil {
		return er
	}

	add.Id = int(addFild.Id)
	return nil
}

func FindFileInfo(f *models.FindFileInfo)  error{

	currentDB, _ := GetDB(GetActiveDbName())

	fi := models.FileInfo{Id:uint64(f.Id)}

	rows, err := currentDB.NamedQuery("SELECT * FROM file_info WHERE id = :id",fi )
	if err != nil {
		return err
	}
	defer rows.Close()

	files := []models.FileInfo{}
	for rows.Next() {
		file := models.FileInfo{}
		rows.StructScan(&file)
		files = append(files, file)
	}

	f.Result.Total= 0
	f.Result.Result = files

	return nil
}

